﻿using Peer;

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MicroMq.Helper
{
    class PeerSession : IPeerSession
    {
        private readonly PeerStream[] streams;

        static Random random = new Random();

        static Dictionary<string, int> Polling = new Dictionary<string, int>();
        public PeerSession(IEnumerable<PeerConnection> connections, string topicId)
        {
            this.streams = connections.Where(a => a.Is(topicId))
                // 主题下 分组 随机分发
                .GroupBy(a => a[topicId]).Select(a => Random(a, topicId).peerStream).ToArray();
        }


        public PeerConnection Random(IEnumerable<PeerConnection> values, string topicId)
        {
            var arr = values.ToArray();
            if (arr.Length == 0)
            {
                throw new ApplicationException("未定义的主题");
            }
            if (arr.Length == 1) return arr[0];
            // 轮询
            int index = -1;
            if (Polling.ContainsKey(topicId))
            {
                index = Polling[topicId];
            }
            if (++index >= arr.Length)
            {
                index = 0;
            }
            Polling[topicId] = index;
            return arr[index];
        }
        public bool Has()
        {
            return streams.Length > 0;
        }

        public async Task SendAsync(byte[] data)
        {
            foreach (PeerStream conn in streams)
            {
                try
                {
                    await conn.SendWithResponseAsync(data);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
}
